#include<stdio.h>
#include<Winsock2.h>
#include<process.h>
#include<String.h>
#include<conio.h>

#define TRUE 1

#pragma comment(lib,"ws2_32.lib")

SOCKET C;

void recvMess(void *);


void color(const unsigned short color1)
{        
        if(color1>=0&&color1<=15)
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color1);
        
    else
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
}



int main(){

    //initialize DLL
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2,2),&wsaData);



    //Create Socket
    SOCKET Client=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);


    //Setup SocketAddress
    struct sockaddr_in ClientAddr;
    memset(&ClientAddr,0,sizeof(ClientAddr));
    ClientAddr.sin_family=AF_INET;
    ClientAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
    ClientAddr.sin_port=htons(8080);



    //Bind Socket
    bind(Client,(SOCKADDR*)&ClientAddr,sizeof(SOCKADDR));


    int log=connect(Client,(SOCKADDR*)&ClientAddr,sizeof(SOCKADDR));
    if(log ==0){
        printf("Connect Successful\n");
    }
        
    
    C=Client;
    _beginthread(recvMess,0,NULL);
    char *str;
    char String[512];
    
    while(TRUE){
        
        gets(String);
        str=String;
        send(Client,str,strlen(str)+sizeof(char),0);
        memset(String,0,sizeof(String));

       
    }


    closesocket(Client);
    closesocket(C);
    WSACleanup();
    return 0;

}

void recvMess(void *args){
    char Buffer[512]={""};
     while(TRUE){
         memset(Buffer,0,sizeof(Buffer));
         recv(C,Buffer,512,0);
         if(Buffer != ""){
            color(9);
            printf("%s\n",Buffer);
            color(7);
        }
    } 
    _endthread();
}
